<?php

class ArticleController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array( 
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('view','create','update','delete','admin','orderby','pview','pcreate','pupdate','pdelete','padmin','porderby'),
				'users'=>array('@'),
			), 
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
            'categorytype'=>0,
		));
	}
    public function actionPview($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
            'categorytype'=>1,
        ));
    }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Article;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
      

		if(isset($_POST['Article']))
		{
			$model->attributes=$_POST['Article'];

            $model->companyid = Yii::app()->user->id;
            //保存上传图片 
            $uploadedimage = CUploadedFile::getInstance($model, 'cover');
            $datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext;
                $uploadedimage->saveAs($uploadfile);
                $model->cover = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
            }
			if($model->save())
				$this->redirect(array('admin','show'=>'1'));
		}
        $data = Column::model()->find('companyid=:id and categorytype=:type',array(':id'=>Yii::app()->user->id,':type'=>0));
        if(empty($data)){
            $column = new Column();
            $column->name='新闻公告分类';
            $column->categorytype='0';
            $column->companyid= Yii::app()->user->id;
            $column->save();
            $model->columnid = $column->id;
        }else{
             $model->columnid = $data->id;
        }
        
		$this->render('create',array(
			'model'=>$model, 
            'categorytype'=>'新闻公告',
		));
	}
    public function actionPcreate()
    {
        $model=new Article;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Article']))
        {
            $model->attributes=$_POST['Article'];

            $model->companyid = Yii::app()->user->id;
            //保存上传图片 
            $uploadedimage = CUploadedFile::getInstance($model, 'cover');
            $datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext;
                $uploadedimage->saveAs($uploadfile);
                $model->cover = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
            }
            if($model->save())
                $this->redirect(array('padmin','show'=>'1'));
        }
        $data = Column::model()->find('companyid=:id and categorytype=:type',array(':id'=>Yii::app()->user->id,':type'=>1));
        if(empty($data)){
            $column = new Column();
            $column->name='产品分类';
            $column->categorytype='1';
            $column->companyid= $model->id;
            $column->save();
            $model->columnid = $column->id;
        }else{
             $model->columnid = $data->id;
        }
        $this->render('create',array(
            'model'=>$model, 
            'categorytype'=>'产品',
        ));
    }

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
      
		if(isset($_POST['Article']))
		{
            $oldpictureUrl = dirname(Yii::app()->basePath).$model->cover;
			$model->attributes=$_POST['Article'];

            $model->companyid = Yii::app()->user->id;
            //保存上传图片 
            $uploadedimage = CUploadedFile::getInstance($model, 'cover');
            $datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext;
                $uploadedimage->saveAs($uploadfile);
                $model->cover = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
                //判断是否旧的logo，如果存在并删除就文件
                if(file_exists($oldpictureUrl)){
                    unlink($oldpictureUrl);
                }
            }
			if($model->save())
				$this->redirect(array('admin','show'=>'1'));
		}

		$this->render('update',array(
			'model'=>$model,
            'categorytype'=>0,
		));
	}
    public function actionPupdate($id)
    {
        $model=$this->loadModel($id);

        if(isset($_POST['Article']))
        {
            $oldpictureUrl = dirname(Yii::app()->basePath).$model->cover;
            $model->attributes=$_POST['Article'];

            $model->companyid = Yii::app()->user->id;
            //保存上传图片 
            $uploadedimage = CUploadedFile::getInstance($model, 'cover');
            $datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext;
                $uploadedimage->saveAs($uploadfile);
                $model->cover = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
                //判断是否旧的logo，如果存在并删除就文件 
                if(file_exists($oldpictureUrl)){
                    unlink($oldpictureUrl);
                }
            }
            if($model->save())
                $this->redirect(array('padmin','show'=>'1'));
        }

        $this->render('update',array(
            'model'=>$model,
            'categorytype'=>1,
        ));
    }

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}
    public function actionPdelete($id)
    {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('padmin'));
    }


    public function actionOrderby($id){
        $sql = 'SELECT max(orderby) as count  FROM ykl_article  limit 1';
        $cnt = Yii::app()->db->createCommand($sql);
        $dataRow = $cnt->query();
        $data = $dataRow->read();
        $model = Article::model()->findByPk($id);
        $model->orderby = $data['count']+1;
        $model->save();
        $this->redirect(array('admin'));
    }


    public function actionPorderby($id){
        $sql = 'SELECT max(orderby) as count  FROM ykl_article  limit 1';
        $cnt = Yii::app()->db->createCommand($sql);
        $dataRow = $cnt->query();
        $data = $dataRow->read();
        $model = Article::model()->findByPk($id);
        $model->orderby = $data['count']+1;
        $model->save();
        $this->redirect(array('padmin'));
    }
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Article');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Article('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Article'])){
            $model->attributes=$_GET['Article'];
        }
        $model->companyid = Yii::app()->user->id; 
        
		$this->render('admin',array(
			'model'=>$model, 
		));
	}
    public function actionPadmin()
    {
        $model=new Article('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Article'])){
            $model->attributes=$_GET['Article'];
        }
        $model->companyid = Yii::app()->user->id;
        $this->render('padmin',array(
            'model'=>$model,
        ));
    }
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Article the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Article::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Article $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='article-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
